﻿#include "messagebox.h"
#include <QApplication>
#include <QScreen>
#include <QEventLoop>

QHMessageBox::QHMessageBox(QWidget *parent)
    : FramelessWindow(parent)
    , m_type(Information)
    , m_buttons(Ok)
    , m_clickedButton(NoButton)
    , m_autoCloseSeconds(0)
    , m_result(0)
    , m_autoCloseTimer(nullptr)
{
    setWindowModality(Qt::ApplicationModal);
    setWindowFlags(windowFlags() | Qt::Window | Qt::Dialog | Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground, false);

    initForm();
    initializeLayout();
    applyStyles();
}

QHMessageBox::QHMessageBox(const QString& title, const QString& content,
                           MessageType type, ButtonTypes buttons, QWidget *parent)
    : QHMessageBox(parent)
{
    setTitle(title);
    setContent(content);
    setMessageType(type);
    setButtons(buttons);
}

QHMessageBox::~QHMessageBox()
{
    if (m_autoCloseTimer) {
        m_autoCloseTimer->stop();
        delete m_autoCloseTimer;
    }
}

void QHMessageBox::setTitle(const QString& title)
{
    m_title = title;
    if (titleLabel) {
        titleLabel->setText(title);
    }
}

void QHMessageBox::setContent(const QString& content)
{
    m_content = content;
    if (contentLabel) {
        contentLabel->setText(content);
    }
}

void QHMessageBox::setMessageType(MessageType type)
{
    m_type = type;
    updateIcon();
}

void QHMessageBox::setButtons(ButtonTypes buttons)
{
    m_buttons = buttons;

    // 隐藏所有按钮
    if (okButton) okButton->setVisible(false);
    if (cancelButton) cancelButton->setVisible(false);
    if (yesButton) yesButton->setVisible(false);
    if (noButton) noButton->setVisible(false);

    // 显示需要的按钮
    if (buttons & Ok && okButton) okButton->setVisible(true);
    if (buttons & Cancel && cancelButton) cancelButton->setVisible(true);
    if (buttons & Yes && yesButton) yesButton->setVisible(true);
    if (buttons & No && noButton) noButton->setVisible(true);
}

void QHMessageBox::setAutoClose(int seconds)
{
    m_autoCloseSeconds = seconds;
    if (seconds > 0) {
        setupAutoClose();
    }
}

QHMessageBox::ButtonType QHMessageBox::clickedButton() const
{
    return m_clickedButton;
}

void QHMessageBox::initForm()
{
    setMinimumSize(DIALOG_MIN_WIDTH, DIALOG_MIN_HEIGHT);

    // 主背景容器
    backgroundWidget = new QWidget(this);
    backgroundWidget->setObjectName("messageBoxBackground");

    // 创建组件
    iconLabel = new QLabel(backgroundWidget);
    iconLabel->setObjectName("messageBoxIcon");
    iconLabel->setFixedSize(54, 54);
    iconLabel->setAlignment(Qt::AlignCenter);

    contentLabel = new QLabel(backgroundWidget);
    contentLabel->setObjectName("messageBoxContent");
    contentLabel->setWordWrap(true);
    contentLabel->setMinimumWidth(320);

    // 创建按钮
    okButton = new QPushButton("确定", backgroundWidget);
    okButton->setObjectName("messageBoxPrimaryBtn");
    okButton->setCursor(Qt::PointingHandCursor);
    okButton->setMinimumWidth(90);
    okButton->setMinimumHeight(38);
    connect(okButton, &QPushButton::clicked, this, &QHMessageBox::onOkClicked);

    cancelButton = new QPushButton("取消", backgroundWidget);
    cancelButton->setObjectName("messageBoxSecondaryBtn");
    cancelButton->setCursor(Qt::PointingHandCursor);
    cancelButton->setMinimumWidth(90);
    cancelButton->setMinimumHeight(38);
    connect(cancelButton, &QPushButton::clicked, this, &QHMessageBox::onCancelClicked);

    yesButton = new QPushButton("是", backgroundWidget);
    yesButton->setObjectName("messageBoxPrimaryBtn");
    yesButton->setCursor(Qt::PointingHandCursor);
    yesButton->setMinimumWidth(90);
    yesButton->setMinimumHeight(38);
    connect(yesButton, &QPushButton::clicked, this, &QHMessageBox::onYesClicked);

    noButton = new QPushButton("否", backgroundWidget);
    noButton->setObjectName("messageBoxSecondaryBtn");
    noButton->setCursor(Qt::PointingHandCursor);
    noButton->setMinimumWidth(90);
    noButton->setMinimumHeight(38);
    connect(noButton, &QPushButton::clicked, this, &QHMessageBox::onNoClicked);
}

void QHMessageBox::initializeLayout()
{
    // 主布局
    QVBoxLayout* containerLayout = new QVBoxLayout(this);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->addWidget(backgroundWidget);

    QVBoxLayout* backgroundLayout = new QVBoxLayout(backgroundWidget);
    backgroundLayout->setSpacing(0);
    backgroundLayout->setContentsMargins(0, 0, 0, 0);

    // 设置标题栏
    setupTitleBar();

    // 内容区域
    QWidget* contentWidget = new QWidget(backgroundWidget);
    contentWidget->setObjectName("messageBoxContentArea");

    QHBoxLayout* contentLayout = new QHBoxLayout(contentWidget);
    contentLayout->setSpacing(20);
    contentLayout->setContentsMargins(30, 30, 30, 25);

    // 图标
    contentLayout->addWidget(iconLabel);

    // 文本
    contentLayout->addWidget(contentLabel, 1);

    backgroundLayout->addWidget(contentWidget);

    // 按钮区域
    buttonContainer = new QWidget(backgroundWidget);
    buttonContainer->setObjectName("messageBoxButtonBar");
    buttonContainer->setFixedHeight(70);

    buttonLayout = new QHBoxLayout(buttonContainer);
    buttonLayout->setContentsMargins(30, 15, 30, 15);
    buttonLayout->setSpacing(12);
    buttonLayout->addStretch();
    buttonLayout->addWidget(cancelButton);
    buttonLayout->addWidget(noButton);
    buttonLayout->addWidget(yesButton);
    buttonLayout->addWidget(okButton);

    backgroundLayout->addWidget(buttonContainer);
}

void QHMessageBox::setupTitleBar()
{
    QWidget* titleBar = new QWidget(backgroundWidget);
    titleBar->setObjectName("messageBoxTitleBar");
    titleBar->setFixedHeight(48);

    QHBoxLayout* titleLayout = new QHBoxLayout(titleBar);
    titleLayout->setContentsMargins(20, 0, 20, 0);
    titleLayout->setSpacing(12);

    titleLabel = new QLabel("提示", titleBar);
    titleLabel->setObjectName("messageBoxTitle");

    QPushButton* btnClose = new QPushButton("×", titleBar);
    btnClose->setObjectName("messageBoxCloseBtn");
    btnClose->setFixedSize(32, 32);
    btnClose->setCursor(Qt::PointingHandCursor);
    connect(btnClose, &QPushButton::clicked, this, [this]() {
        m_clickedButton = NoButton;
        m_result = 0;
        emit rejected();
        close();
    });

    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(btnClose);

    setTitlebarWidgets({titleBar});

    // 将标题栏添加到背景布局
    QVBoxLayout* bgLayout = qobject_cast<QVBoxLayout*>(backgroundWidget->layout());
    if (bgLayout) {
        bgLayout->insertWidget(0, titleBar);
    }
}

void QHMessageBox::applyStyles()
{
    setStyleSheet(R"(
        /* 主背景 */
        QWidget#messageBoxBackground {
            background-color: #2C2C2E;
            border-radius: 8px;
            border: 1px solid #3C3C3E;
        }

        /* 标题栏 */
        QWidget#messageBoxTitleBar {
            background-color: #3C3C3E;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            border-bottom: 1px solid #555;
        }

        QLabel#messageBoxTitle {
            color: #FFFFFF;
            font-size: 14px;
            font-weight: bold;
        }

        QPushButton#messageBoxCloseBtn {
            background: transparent;
            color: #AAAAAA;
            border: none;
            font-size: 24px;
            font-weight: bold;
            border-radius: 4px;
        }

        QPushButton#messageBoxCloseBtn:hover {
            background: #E74C3C;
            color: #FFFFFF;
        }

        /* 内容区域 */
        QWidget#messageBoxContentArea {
            background: transparent;
        }

        QLabel#messageBoxIcon {
            background: transparent;
        }

        QLabel#messageBoxContent {
            color: #E0E0E0;
            font-size: 14px;
            background: transparent;
        }

        /* 按钮区域 */
        QWidget#messageBoxButtonBar {
            background: transparent;
            border-top: 1px solid #3C3C3E;
        }

        QPushButton#messageBoxPrimaryBtn {
            background-color: #4CAF50;
            color: #FFFFFF;
            border: none;
            border-radius: 6px;
            padding: 10px 24px;
            font-size: 13px;
            font-weight: bold;
        }

        QPushButton#messageBoxPrimaryBtn:hover {
            background-color: #66BB6A;
        }

        QPushButton#messageBoxPrimaryBtn:pressed {
            background-color: #388E3C;
        }

        QPushButton#messageBoxSecondaryBtn {
            background-color: #3C3C3E;
            color: #FFFFFF;
            border: 1px solid #555;
            border-radius: 6px;
            padding: 10px 24px;
            font-size: 13px;
        }

        QPushButton#messageBoxSecondaryBtn:hover {
            background-color: #4A4A4C;
            border-color: #4CAF50;
        }

        QPushButton#messageBoxSecondaryBtn:pressed {
            background-color: #555;
        }
    )");
}

void QHMessageBox::setupAutoClose()
{
    if (!m_autoCloseTimer) {
        m_autoCloseTimer = new QTimer(this);
        connect(m_autoCloseTimer, &QTimer::timeout, this, &QHMessageBox::onAutoCloseTimeout);
    }
    m_autoCloseTimer->start(m_autoCloseSeconds * 1000);
}

void QHMessageBox::updateIcon()
{
    if (!iconLabel) return;

    QString iconSymbol = getIconSymbol(m_type);
    QString iconColor = getIconColor(m_type);

    iconLabel->setStyleSheet(QString(
        "QLabel#messageBoxIcon { "
        "  color: %1; "
        "  font-size: 48px; "
        "  font-weight: bold; "
        "  background: transparent; "
        "}"
    ).arg(iconColor));

    iconLabel->setText(iconSymbol);
}

QString QHMessageBox::getIconSymbol(MessageType type)
{
    switch (type) {
        case Information:
            return "ℹ";  // Unicode info symbol
        case Warning:
            return "⚠";  // Unicode warning symbol
        case Error:
            return "✖";  // Unicode X symbol
        case Success:
            return "✓";  // Unicode check mark
        case Question:
            return "?";  // Question mark
        default:
            return "ℹ";
    }
}

QString QHMessageBox::getIconColor(MessageType type)
{
    switch (type) {
        case Information:
            return "#2196F3";  // 蓝色
        case Warning:
            return "#FF9800";  // 橙色
        case Error:
            return "#F44336";  // 红色
        case Success:
            return "#4CAF50";  // 绿色
        case Question:
            return "#9C27B0";  // 紫色
        default:
            return "#2196F3";
    }
}

// 槽函数
void QHMessageBox::onOkClicked()
{
    m_clickedButton = Ok;
    m_result = 1;
    emit buttonClicked(Ok);
    emit accepted();
    close();
}

void QHMessageBox::onCancelClicked()
{
    m_clickedButton = Cancel;
    m_result = 0;
    emit buttonClicked(Cancel);
    emit rejected();
    close();
}

void QHMessageBox::onYesClicked()
{
    m_clickedButton = Yes;
    m_result = 1;
    emit buttonClicked(Yes);
    emit accepted();
    close();
}

void QHMessageBox::onNoClicked()
{
    m_clickedButton = No;
    m_result = 0;
    emit buttonClicked(No);
    emit rejected();
    close();
}

void QHMessageBox::onAutoCloseTimeout()
{
    if (m_autoCloseTimer) {
        m_autoCloseTimer->stop();
    }
    close();
}

int QHMessageBox::exec()
{
    // 居中显示
    if (parentWidget()) {
        QPoint parentCenter = parentWidget()->geometry().center();
        move(parentCenter - rect().center());
    } else {
        QScreen* screen = QGuiApplication::primaryScreen();
        QRect screenGeometry = screen->availableGeometry();
        move(screenGeometry.center() - rect().center());
    }

    show();
    raise();
    activateWindow();

    QEventLoop eventLoop;
    connect(this, &QHMessageBox::accepted, &eventLoop, &QEventLoop::quit);
    connect(this, &QHMessageBox::rejected, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

    return m_result;
}

// 静态便捷方法
void QHMessageBox::information(QWidget *parent, const QString& title, const QString& content)
{
    QHMessageBox* msgBox = new QHMessageBox(title, content, Information, Ok, parent);
    msgBox->setAttribute(Qt::WA_DeleteOnClose);
    msgBox->exec();
}

void QHMessageBox::warning(QWidget *parent, const QString& title, const QString& content)
{
    QHMessageBox* msgBox = new QHMessageBox(title, content, Warning, Ok, parent);
    msgBox->setAttribute(Qt::WA_DeleteOnClose);
    msgBox->exec();
}

void QHMessageBox::error(QWidget *parent, const QString& title, const QString& content)
{
    QHMessageBox* msgBox = new QHMessageBox(title, content, Error, Ok, parent);
    msgBox->setAttribute(Qt::WA_DeleteOnClose);
    msgBox->exec();
}

void QHMessageBox::success(QWidget *parent, const QString& title, const QString& content)
{
    QHMessageBox* msgBox = new QHMessageBox(title, content, Success, Ok, parent);
    msgBox->setAttribute(Qt::WA_DeleteOnClose);
    msgBox->exec();
}

bool QHMessageBox::question(QWidget *parent, const QString& title, const QString& content)
{
    QHMessageBox msgBox(title, content, Question, Yes | No, parent);
    int result = msgBox.exec();
    return result == 1;  // Yes 返回 true，No 返回 false
}
